using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AutoStartManager.Models;

namespace AutoStartManager.Services
{
    /// <summary>
    /// 配置文件管理器
    /// </summary>
    public class ConfigManager
    {
        private readonly string _configFilePath;
        private readonly string _configDirectory;

        public ConfigManager()
        {
            _configDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "AutoStartManager");
            _configFilePath = Path.Combine(_configDirectory, "config.conf");
            
            // 确保配置目录存在
            if (!Directory.Exists(_configDirectory))
            {
                Directory.CreateDirectory(_configDirectory);
            }
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        public void SaveConfig(List<ManagedApp> apps, bool autoStartEnabled)
        {
            try
            {
                var lines = new List<string>
                {
                    "[General]",
                    $"AutoStartEnabled={autoStartEnabled}",
                    "",
                    "[ManagedApps]"
                };

                foreach (var app in apps)
                {
                    lines.Add($"AppName={app.Name}");
                    lines.Add($"ExecutablePath={app.ExecutablePath}");
                    lines.Add($"Arguments={app.Arguments}");
                    lines.Add($"WorkingDirectory={app.WorkingDirectory}");
                    lines.Add($"IsEnabled={app.IsEnabled}");
                    lines.Add("---");
                }

                File.WriteAllLines(_configFilePath, lines);
            }
            catch (Exception ex)
            {
                throw new Exception($"保存配置文件失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 加载配置
        /// </summary>
        public (List<ManagedApp> apps, bool autoStartEnabled) LoadConfig()
        {
            var apps = new List<ManagedApp>();
            var autoStartEnabled = false;

            if (!File.Exists(_configFilePath))
            {
                return (apps, autoStartEnabled);
            }

            try
            {
                var lines = File.ReadAllLines(_configFilePath);
                var currentApp = new ManagedApp();
                var inGeneralSection = false;
                var inAppsSection = false;

                foreach (var line in lines)
                {
                    var trimmedLine = line.Trim();
                    
                    if (string.IsNullOrEmpty(trimmedLine))
                        continue;

                    if (trimmedLine == "[General]")
                    {
                        inGeneralSection = true;
                        inAppsSection = false;
                        continue;
                    }

                    if (trimmedLine == "[ManagedApps]")
                    {
                        inGeneralSection = false;
                        inAppsSection = true;
                        continue;
                    }

                    if (inGeneralSection)
                    {
                        if (trimmedLine.StartsWith("AutoStartEnabled="))
                        {
                            bool.TryParse(trimmedLine.Substring("AutoStartEnabled=".Length), out autoStartEnabled);
                        }
                    }
                    else if (inAppsSection)
                    {
                        if (trimmedLine == "---")
                        {
                            if (!string.IsNullOrEmpty(currentApp.Name))
                            {
                                apps.Add(currentApp);
                            }
                            currentApp = new ManagedApp();
                        }
                        else if (trimmedLine.StartsWith("AppName="))
                        {
                            currentApp.Name = trimmedLine.Substring("AppName=".Length);
                        }
                        else if (trimmedLine.StartsWith("ExecutablePath="))
                        {
                            currentApp.ExecutablePath = trimmedLine.Substring("ExecutablePath=".Length);
                        }
                        else if (trimmedLine.StartsWith("Arguments="))
                        {
                            currentApp.Arguments = trimmedLine.Substring("Arguments=".Length);
                        }
                        else if (trimmedLine.StartsWith("WorkingDirectory="))
                        {
                            currentApp.WorkingDirectory = trimmedLine.Substring("WorkingDirectory=".Length);
                        }
                        else if (trimmedLine.StartsWith("IsEnabled="))
                        {
                            bool.TryParse(trimmedLine.Substring("IsEnabled=".Length), out bool isEnabled);
                            currentApp.IsEnabled = isEnabled;
                        }
                    }
                }

                // 添加最后一个应用
                if (!string.IsNullOrEmpty(currentApp.Name))
                {
                    apps.Add(currentApp);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"加载配置文件失败: {ex.Message}", ex);
            }

            return (apps, autoStartEnabled);
        }

        /// <summary>
        /// 获取配置文件路径
        /// </summary>
        public string GetConfigFilePath()
        {
            return _configFilePath;
        }
    }
}